<?
/********************************************************************************************************/
/* This class represents generic collection of items (objects) ******************************************/
/********************************************************************************************************/

class Collection {
    private $members;
    private $on_load;
    private $is_loaded;
    
    public function __counstruct() {
	$this->members=array();
	$this->is_loaded=false;
    }


    public function add_item($obj,$key=false) {
	$this->_check_callback();
	if ($key) {
	    if (!isset($this->members[$key])) {
		$this->members[$key]=$obj;
	    }
	} else {
	    $this->members[]=$obj;
	}
    }
    
    public function remove_item($key) {
	$this->_check_callback();
	if (isset($this->members[$key])) {
	    unset($this->members[$key]);
	}
    }

    public function get_item($key) {
	$this->_check_callback();
	if (isset($this->members[$key])) {
	    return $this->members[$key];
	}
	return false;
    }

    public function keys() {
	$this->_check_callback();
	return array_keys($this->members);
    }

    public function length() {
	$this->_check_callback();
	return sizeof($this->members);
    }

    public function exists($key) {
	$this->_check_callback();
	return isset($this->members[$key]);
    }

    public function set_load_callback($function_name,$obj_or_class=false) {
	if ($obj_or_class) {
	    $callback=array($obj_or_class,$function_name);
	} else {
	    $callback=$function_name;
	}
	if (!is_callable($callback,false,$callable_name)) {
//	    echo "Non callable<br>";
	    return false;
	}
	$this->on_load=$callback;
//	echo "Callable<br>";
	return true;
    }
    
    private function _check_callback() {
	if (isset($this->on_load) && !$this->is_loaded) {
	    call_user_func($this->on_load);
	    $this->is_loaded=true;
	}
    }
}

?>
